import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

interface Response<T> {
  data: T;
  code: number;
  message: string;
  timestamp: string;
}

@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, Response<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<Response<T>> {
    return next.handle().pipe(
      map((data) => {
        // 检查数据是否已经是标准响应格式
        if (data && typeof data === 'object' && 'code' in data && 'message' in data && 'timestamp' in data) {
          // 如果已经是标准格式，直接返回，避免重复包装
          return data;
        }
        
        // 否则，包装为标准响应格式
        return {
          data,
          code: 0,
          message: '操作成功',
          timestamp: new Date().toISOString(),
        };
      }),
    );
  }
}
